﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using TimeTracker.Core.Domain.Entities;
using TimeTracker.Web.Admin.Interface;
using TimeTracker.Web.Admin.Presenter;

namespace TimeTracker.Web.Admin
{
    public partial class Korisnici : System.Web.UI.Page, IKorisniciView
    {
        private KorisniciPresenter _presenter;

        protected void Page_Load(object sender, EventArgs e)
        {
            _presenter = new KorisniciPresenter();
            _presenter.Init(this);
        }

        public void PokaziKorisnike(IList<Korisnik> korisnici)
        {
            gvKorisnici.DataSource = korisnici;
            gvKorisnici.DataBind();
        }

        protected void GridViewKorisnici_OnRowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Dodaj"))
            {
                var imeKorisnika = (TextBox)gvKorisnici.FooterRow.FindControl("tbNovoIme");
                var lozinka = (TextBox) gvKorisnici.FooterRow.FindControl("tbNovaLozinka");
                var email = (TextBox) gvKorisnici.FooterRow.FindControl("tbNoviEmail");

                _presenter.DodajKorisnika(imeKorisnika.Text, lozinka.Text, email.Text);
                _presenter.Init(this);
            }
            if (e.CommandName.Equals("Otkazi"))
            {
                gvKorisnici.EditIndex = -1;
            }
        }

        protected void GridViewKorisnici_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var korisnikId = Convert.ToInt32(gvKorisnici.DataKeys[e.RowIndex].Values[0].ToString());
            _presenter.ObrisiKorisnika(korisnikId);
            _presenter.Init(this);
        }

        protected void GridViewKorisnici_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            gvKorisnici.EditIndex = e.NewEditIndex;
            _presenter.Init(this);
        }

        protected void GridViewKorisnici_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvKorisnici.EditIndex = -1;
            _presenter.Init(this);
        }

        protected void GridViewKorisnici_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var korisnikId = (int)gvKorisnici.DataKeys[e.RowIndex].Value;

            var imeKorisnika = (TextBox)gvKorisnici.Rows[e.RowIndex].FindControl("tbIme");
            var lozinka = (TextBox)gvKorisnici.Rows[e.RowIndex].FindControl("tbLozinka");
            var email = (TextBox)gvKorisnici.Rows[e.RowIndex].FindControl("tbEmail");

            _presenter.AzurirajKorisnika(korisnikId, imeKorisnika.Text, lozinka.Text, email.Text);

            gvKorisnici.EditIndex = -1;
        }
    }
}
